/* cl.ext.given.report 0.1*/
(
    function (factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery',"echarts","eChartChina","eChartTheme"], function($,echartsjs) {
                factory($,echartsjs);
            });
        } else if (typeof module === 'object' && module.exports) {
            var eChartsJs = require('echarts');
            var eChartChinaJs = require('eChartChina');
            var eChartThemeJs = require('eChartTheme');
            module.exports = function( root, jQuery ) {
                if ( jQuery === undefined ) {
                    if ( typeof window !== 'undefined' ) {
                        jQuery = require('jquery');
                    }
                    else {
                        jQuery = require('jquery')(root);
                    }
                }
                factory(jQuery,eChartsJs,eChartChinaJs,eChartThemeJs);
            };
        } else {
            factory(jQuery);
        }
    }(
    function ($,echarts){
        var ReportExtModal = function() {};
        ReportExtModal.prototype = {
            initBind: function (pageOption, listData, cb) {
                var self = this;
                var pageData = {};
                if(pageOption.chart.infoDefault){
                    var arrTitleName={};
                    pageOption.chart.infoDefault.titleSort=$.map(pageOption.chart.infoDefault.titles,function(info){
                        arrTitleName[info.id]=info.name;
                        return info.id
                    });
                    pageOption.chart.infoDefault.titleName=arrTitleName;
                }
                pageData.para = pageOption;
                if (!$.ExtCommon.isCheckEmpty(listData)) {
                    var json ={list:listData};
                    pageData.original = json;
                    pageData.chartdata = json.list.length === 0
                        ? {}
                        : self.structChartDataListToJson(json.list, {
                            name: pageOption.chart.keyword,
                            nameformat: pageOption.type,
                            len: pageOption.chart.xAxisLen,
                            showOther: pageOption.chart.xOther,
                            isDesc: pageOption.chart.isDesc,
                            showIndexName:pageOption.chart.showIndexName,
                            convertName:pageOption.chart.convertName
                        }, pageOption.chart.infoDefault.titleName)
                } else {
                    pageData.original = {list: []};
                    pageData.chartdata = {};
                }
                if (cb)cb(pageData)

            },
            getChartTabsQueue: function (value, json) {
                var info = json.infoChartTabsQueue;
                var list = info.list.arrclone();
                value = value.toString();
                var idx = list.indexOf(value);
                if (idx > -1) {
                    list.splice(idx, 1)
                } else {
                    list.push(value);
                    if (list.length > info.count) {
                        list.splice(0, 1)
                    }
                }
                if (list.length > 0)json.infoChartTabsQueue.list = list;
                return list;
            },
            structChartDataListToJson: function (list, xConfig, yConfig) {
                var xInfo = {name: [], allname: []};
                var yInfo = {};
                var otherInfo = {};
                var dataInfo = [];
                var yArrKey = [];
                for (var yc in yConfig) {
                    if (yConfig.hasOwnProperty(yc)) {
                        yInfo[yc] = {name: yConfig[yc], data: [], alldata: []};
                        yArrKey.push(yc);
                        otherInfo[yc] = 0;
                    }
                }
                var xi = 0;
                var xlen = list.length;
                if (xConfig.len > 0) {
                    if (xConfig.isDesc) {
                        xi = list.length > xConfig.len ? list.length - xConfig.len : 0;
                        xlen = list.length;
                    } else {
                        xi = 0;
                        xlen = list.length > xConfig.len ? xConfig.len : list.length
                    }
                }
                $.each(list, function (i, info) {
                    if (i >= xi && i < xlen) {
                        dataInfo.push(info);
                    }
                    for (var k in info) {
                        if (info.hasOwnProperty(k)) {
                            var value = info[k];
                            if (k == xConfig.name) {
                                xInfo.allname.push(value);
                                if (i >= xi && i < xlen) {
                                    var nameValue = value;
                                    if(!$.ExtCommon.isCheckEmpty(xConfig.showIndexName) && !$.ExtCommon.isCheckEmpty(xConfig.convertName) && xConfig.showIndexName.indexOf(value.toString())>-1){
                                        nameValue=info[xConfig.convertName]
                                    }
                                    switch (xConfig.nameformat) {
                                        case "day":
                                            nameValue = $.ExtMoment.initFormat({value: value, format: "MM.DD"});
                                            break;
                                    }
                                    xInfo.name.push(nameValue);
                                }
                            }
                            if (yArrKey.indexOf(k) > -1) {
                                yInfo[k].alldata.push(value);
                                if (i >= xi && i < xlen) {
                                    yInfo[k].data.push(value)
                                } else {
                                    otherInfo[k] += info[k];
                                }
                            }
                        }
                    }
                });
                return {x: xInfo, y: yInfo, data: dataInfo, otherInfo: otherInfo};
            },
            getChartOption: function (json,options) {
                var self = this;
                var arrJsonKey = self.getCharSeriesKey(json);
                var optionChart = self.getCompositeChartInfo(arrJsonKey, json);
                var chartBaseInfo = self.optionChartBase(options,json);
                if(!$.ExtCommon.isCheckEmpty(chartBaseInfo.legend)){chartBaseInfo.legend.data = optionChart.legendData;}
                chartBaseInfo.xAxis.data = optionChart.xNames;
                chartBaseInfo.yAxis = optionChart.yaxis;
                chartBaseInfo.series = optionChart.series;
                return chartBaseInfo;
            },
            getCharSeriesKey: function (json) {
                var paraTypeTopLevel = ["day", "hour"];
                var arrNameLevel=json.para.chart.infoDefault.titleSort;
                var paraType = json.para.type;
                var chartConfig = json.para.chart;
                var arrlist = json.infoChartTabsQueue.list;
                var arrKey = $.map(arrlist, function (name) {
                    var type = chartConfig.seriesType;
                    return {name: name, type: type, len: chartConfig.xAxisLen, isShowOther: chartConfig.xOther}
                });
                if(arrKey.length === 2){
                    var k1 = arrNameLevel.indexOf(arrKey[0].name);
                    var k2 = arrNameLevel.indexOf(arrKey[1].name);
                    if(paraTypeTopLevel.indexOf(paraType) === -1){
                        if (k1 > k2) {
                            arrKey[0].type = "line";
                            arrKey[1].type = "bar";
                        } else {
                            arrKey[0].type = "bar";
                            arrKey[1].type = "line"
                        }
                    }
                    if(k1 > k2){arrKey=arrKey.reverse()}
                }
                return arrKey
            },
            getCompositeChartInfo: function (arrjson, json) {
                var self = this;
                var legendData = [];
                var series = [];
                var yaxis = [];
                var xNames = [""];
                var datajson=json.chartdata;
                var titleNames=json.para.chart.infoDefault.titleName;
                var space=$.ExtCommon.isCheckEmpty(json.para.chart["space"])?5:json.para.chart["space"];
                $.each(arrjson, function (i, arr) {
                    if ($.isEmptyObject(datajson)) {
                        var tempEmptyName = titleNames[arr.name];
                        legendData.push(tempEmptyName);
                        var tempEmptyData = [];
                        for (var a = 0; a < arr.len; a++) tempEmptyData.push(0);
                        if (arr.isShowOther) tempEmptyData.push(0);
                        series.push({name: tempEmptyName, type: arr.type, yAxisIndex: i, data: tempEmptyData});
                        yaxis.push({type: 'value', min: 0, max: 1, interval: 1});
                    } else {
                        var info = datajson.y[arr.name];
                        var tempName = info.name;
                        legendData.push(tempName);
                        var tempData = info.data.arrclone();
                        if (arr.isShowOther && arr.len < info.alldata.length) tempData.push(datajson.otherInfo[arr.name].toDecimal2());
                        series.push({name: tempName, type: arr.type, yAxisIndex: i, data: tempData});
                        var maxRatio = i === 1 ? 1.5 : 1;
                        var infoAxis = self.calculateChartScale(tempData, space, maxRatio);
                        yaxis.push({type: 'value', min: 0, max: infoAxis.max, interval: infoAxis.interval});
                    }
                });
                if (!$.isEmptyObject(datajson)) {
                    xNames = datajson.x.name.arrclone();
                    if (arrjson[0].isShowOther && arrjson[0].len < datajson.x.allname.length) xNames.push("其他");
                }
                return {legendData: legendData, series: series, yaxis: yaxis, xNames: xNames}
            },
            calculateChartScale: function (arrData, space, maxRatio) {
                space = parseInt(space && space > 0 ? space : 5);
                var tempMax = Math.max.apply(null, arrData);
                var tempInterval = maxRatio > 1 ? tempMax * maxRatio / space : tempMax / space;
                var interval = Math.ceil(tempInterval);
                if (tempInterval > 1) {
                    interval = interval + Math.ceil(tempInterval / 100) * 2;
                } else {
                    interval = (Math.ceil(tempInterval * 100) + 1) / 100
                }
                var max = (space * interval).toFixed(2);
                return {max: max, interval: interval}
            },
            optionChartBase: function (options,chartJson) {
                var isOmit=chartJson.para.chart["isOmit"];
                isOmit=typeof isOmit==="boolean"?isOmit:true;
                switch(chartJson.para.type){
                    case "hour":
                        isOmit=false;
                        break;
                    case "day":
                        isOmit=false;
                        break;
                }
                var xAxisInterval=isOmit?0:(chartJson.para.type==="hour"?0:"auto");
                var optionBase={
                    title: {text: ''},
                    tooltip: {trigger: 'axis',
                        formatter: function (params){//params, ticket, callback
                            var series=[];
                            var title=params[0].name;
                            var keyHover=chartJson.para.chart.hoverTitle;
                            var keyword=chartJson.para.chart.keyword;
                            var titleHover=chartJson.chartdata.data[params[0].dataIndex][keyHover];
                            switch(chartJson.para.type){
                                case "hour":
                                    title=$.ExtCommon.getHourInterval(parseInt(titleHover));
                                    break;
                                case "day":
                                    title=titleHover;
                                    break;
                                default:
                                    if(keyHover!==keyword){
                                        title=$.ExtCommon.getStringConnect("{0} - {1}",[params[0].name,titleHover]);
                                    }
                            }
                            series.push(title);
                            var colorEl = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:{0}"></span>';
                            for(var i=0;i<params.length;i++){
                                var info=params[i];
                                var html=$.ExtCommon.getStringConnect(colorEl,[info.color])
                                    +$.ExtCommon.encodeHTML(info.seriesName)
                                    + ' : '
                                    +$.ExtCommon.addCommas(info.value);
                                series.push(html)
                            }
                            return series.join("<br />");
                        }
                    },
                    legend: {data: []},
                    grid: {top:"30px",left: '1%', right: '1%', bottom: '1%', containLabel: true},
                    xAxis: {
                        type: 'category', boundaryGap: true,
                        axisLabel:{interval:xAxisInterval,formatter:function (value) {//value,index
                            if(chartJson.para.element){
                                if(isOmit){
                                    var totalWidth=chartJson.para.element.width();
                                    //200 左右间距;12 中文字体大小,6 英文字体大小 估算  do 避免太过拥挤 使用 18,9
                                    var w=parseInt((totalWidth-200)/chartJson.chartdata.data.length);
                                    var arrTemp=value.toString().split("");
                                    var arrValue=[];
                                    var fw=0;
                                    for(var i=0;i<arrTemp.length;i++){
                                        fw+=/.*[\u4e00-\u9fa5]+.*$/.test(arrTemp[i])?18:9;
                                        if(fw>w){
                                            break;
                                        }else{
                                            arrValue.push(arrTemp[i]);
                                        }
                                    }
                                    var out="";
                                    if(arrTemp.length===arrValue.length){
                                        out=value;
                                    }else{
                                        out=arrValue.slice(0,arrValue.length-3).join("")+"...";
                                    }
                                    return out;
                                }else{
                                    return value;
                                }
                            }else{
                                return value;
                            }
                        }},
                        splitLine: {show: false}, data: []},
                    yAxis: [],
                    series: []
                };
                if(!$.ExtCommon.isCheckEmpty(options)){
                    optionBase =$.ExtCommon.initMergeJson(optionBase,options);
                    if(options.infoExt){
                        if(options.infoExt["hideLegend"]){optionBase.legend={};}
                    }
                }
                return optionBase
            },
            getChartListToOptionInfo: function (list, valueKey,key) {
                key=key||"key";
                var legend = [];
                var seriesData = [];
                var arrValue = [0];
                $.each(list, function (i, info) {
                    legend.push(info[key]);
                    seriesData.push({value: info[valueKey], name: info[key]});
                    arrValue.push(parseInt(info[valueKey]));
                });
                var maxValue = Math.max.apply(null, arrValue);
                var sortArr = arrValue.arrclone().sort(function (a, b) {
                    return b - a;
                });
                return {legend: legend, seriesData: seriesData, maxValue: maxValue, oldArr: arrValue, sortArr: sortArr}
            },
            initECharts:function(obj,option){
                echarts.init(obj,"macarons").setOption(option);
            }
        };
        $.ExtReport = new ReportExtModal;
        $.ExtReport.Constructor = ReportExtModal;
        return ReportExtModal;
    })
);